const api = require('../../utils/api.js')
const permissionUtils = require('../../utils/permissions.js')
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    list: [],
    page: 1,
    limit: 10,
    total: 0,
    totalPages: 0,
    searchKeyword: '',
    statusIndex: 0,
    statusOptions: ['全部', '启用', '禁用'],
    loading: false,
    showAddModal: false,
    showEditModal: false,
    currentAdmin: null,
    showPassword: false,
    showConfirmPassword: false,
    showEditPassword: false,
    permissionModules: [
      { key: 'product_manage', name: '产品管理' },
      { key: 'model_manage', name: '型号管理' },
      { key: 'process_manage', name: '工序管理' },
      { key: 'price_manage', name: '价格管理' },
      { key: 'order_manage', name: '订单管理' },
      { key: 'allocation_manage', name: '分工管理' },
      { key: 'report_manage', name: '报工管理' },
      { key: 'active_report_manage', name: '主动报工管理' },
      { key: 'production_plan_manage', name: '生产计划管理' },
      { key: 'admin_manage', name: '管理员管理' }
    ],
    permissionActions: [
      { key: 'view', name: '查看' },
      { key: 'add', name: '新增' },
      { key: 'edit', name: '编辑' },
      { key: 'delete', name: '删除' },
      { key: 'batch', name: '批量操作' },
      { key: 'audit', name: '审核' }
    ]
  },

  onLoad() {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/admin-manage/admin-manage')) {
      return
    }
    
    this.loadData()
  },

  onShow() {
    this.loadData()
  },

  // 检查是否有权限执行某个操作
  hasPermission(module, action) {
    const app = getApp();
    const adminInfo = app.globalData.adminInfo;
    if (!adminInfo || !adminInfo.id) {
      return false;
    }
    
    // 只有超级管理员可以管理其他管理员
    return adminInfo.id == 1;
  },

  // 显示权限不足提示
  showPermissionDenied(module, action) {
    wx.showModal({
      title: '权限不足',
      content: `您没有权限执行此操作：${module}.${action}`,
      showCancel: false
    });
  },

  onPullDownRefresh() {
    this.setData({
      page: 1
    })
    this.loadData().then(() => {
      wx.stopPullDownRefresh()
    })
  },

  onReachBottom() {
    if (this.data.page < this.data.totalPages) {
      this.setData({
        page: this.data.page + 1
      })
      this.loadData(true)
    }
  },

  async loadData(append = false) {
    if (this.data.loading) return

    // 检查查看权限
    if (!this.hasPermission('admin_manage', 'view')) {
      this.showPermissionDenied('admin_manage', 'view');
      return;
    }

    this.setData({ loading: true })

    try {
      const params = {
        page: this.data.page,
        limit: this.data.limit
      }

      if (this.data.searchKeyword) {
        params.username = this.data.searchKeyword
      }

      if (this.data.statusIndex > 0) {
        params.status = this.data.statusIndex - 1
      }

      console.log('请求参数:', params);
      
      // 直接使用wx.request，不依赖API模块
      const app = getApp()
      const globalData = app ? app.globalData : { token: '', baseUrl: '' }
      
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: globalData.baseUrl + '/getAdminList',
          method: 'GET',
          data: params,
          header: {
            'content-type': 'application/json',
            'Authorization': globalData.token ? 'Bearer ' + globalData.token : ''
          },
          success: (res) => {
            if (res.statusCode === 200) {
              resolve(res.data)
            } else {
              reject(res)
            }
          },
          fail: reject
        })
      })

      if (res.code === 1) {
        const list = res.data.list.map(item => ({
          ...item,
          createtime_text: this.formatTime(item.createtime),
          status_text: item.status == 1 ? '启用' : '禁用'
        }))

        this.setData({
          list: append ? [...this.data.list, ...list] : list,
          total: res.data.total,
          totalPages: Math.ceil(res.data.total / this.data.limit)
        })
      } else {
        wx.showToast({
          title: res.msg || '加载失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('加载管理员列表失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
  },

  onSearch() {
    this.setData({
      page: 1
    })
    this.loadData()
  },

  onStatusChange(e) {
    this.setData({
      statusIndex: parseInt(e.detail.value),
      page: 1
    })
    this.loadData()
  },

  onAdd() {
    // 检查添加权限
    if (!this.hasPermission('admin_manage', 'add')) {
      this.showPermissionDenied('admin_manage', 'add');
      return;
    }
    
    // 跳转到新增管理员页面
    wx.navigateTo({
      url: '/pages/admin-add/admin-add'
    })
  },

  async onEdit(e) {
    // 检查编辑权限
    if (!this.hasPermission('admin_manage', 'edit')) {
      this.showPermissionDenied('admin_manage', 'edit');
      return;
    }
    
    const item = e.currentTarget.dataset.item
    
    // 不能编辑超级管理员
    if (item.id == 1) {
      wx.showToast({
        title: '不能编辑超级管理员',
        icon: 'none'
      })
      return
    }
    
    // 跳转到编辑管理员页面
    wx.navigateTo({
      url: `/pages/admin-edit/admin-edit?id=${item.id}`
    })
  },

  onDelete(e) {
    // 检查删除权限
    if (!this.hasPermission('admin_manage', 'delete')) {
      this.showPermissionDenied('admin_manage', 'delete');
      return;
    }
    
    const item = e.currentTarget.dataset.item
    
    // 不能删除超级管理员
    if (item.id == 1) {
      wx.showToast({
        title: '不能删除超级管理员',
        icon: 'none'
      })
      return
    }
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除管理员"${item.nickname || item.username}"吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            // 直接使用wx.request删除管理员
            const app = getApp()
            const globalData = app ? app.globalData : { token: '', baseUrl: '' }
            
            const result = await new Promise((resolve, reject) => {
              wx.request({
                url: globalData.baseUrl + '/deleteAdmin',
                method: 'POST',
                data: { id: item.id },
                header: {
                  'content-type': 'application/json',
                  'Authorization': globalData.token ? 'Bearer ' + globalData.token : ''
                },
                success: (res) => {
                  if (res.statusCode === 200) {
                    resolve(res.data)
                  } else {
                    reject(res)
                  }
                },
                fail: reject
              })
            })

            if (result.code === 1) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
              this.loadData()
            } else {
              wx.showToast({
                title: result.msg || '删除失败',
                icon: 'none'
              })
            }
          } catch (error) {
            console.error('删除管理员失败:', error)
            wx.showToast({
              title: '删除失败',
              icon: 'none'
            })
          }
        }
      }
    })
  },

  // 获取默认权限配置
  getDefaultPermissions() {
    const permissions = {}
    this.data.permissionModules.forEach(module => {
      permissions[module.key] = ['view'] // 默认只有查看权限
    })
    console.log('默认权限配置:', permissions)
    return permissions
  },

  // 输入框变化处理
  onInputChange(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    const currentAdmin = { ...this.data.currentAdmin }
    currentAdmin[field] = value
    
    this.setData({
      currentAdmin: currentAdmin
    })
  },

  // 状态选择器变化处理
  onStatusPickerChange(e) {
    const currentAdmin = { ...this.data.currentAdmin }
    currentAdmin.status = parseInt(e.detail.value)
    
    this.setData({
      currentAdmin: currentAdmin
    })
  },

  // 切换密码显示/隐藏
  togglePasswordVisibility() {
    this.setData({
      showPassword: !this.data.showPassword
    })
  },

  // 切换确认密码显示/隐藏
  toggleConfirmPasswordVisibility() {
    this.setData({
      showConfirmPassword: !this.data.showConfirmPassword
    })
  },

  // 切换编辑密码显示/隐藏
  toggleEditPasswordVisibility() {
    this.setData({
      showEditPassword: !this.data.showEditPassword
    })
  },

  // 权限选择处理
  onPermissionChange(e) {
    const { module, action } = e.currentTarget.dataset
    console.log(`权限变更触发: module=${module}, action=${action}`)
    
    const currentAdmin = { ...this.data.currentAdmin }
    
    // 确保permissions对象存在
    if (!currentAdmin.permissions) {
      console.log('创建新的permissions对象')
      currentAdmin.permissions = {}
    }
    
    // 确保模块权限数组存在且为数组
    if (!currentAdmin.permissions[module] || !Array.isArray(currentAdmin.permissions[module])) {
      console.log(`初始化模块 ${module} 的权限数组`)
      currentAdmin.permissions[module] = []
    }
    
    const index = currentAdmin.permissions[module].indexOf(action)
    if (index > -1) {
      console.log(`移除权限: ${module}.${action}`)
      currentAdmin.permissions[module].splice(index, 1)
    } else {
      console.log(`添加权限: ${module}.${action}`)
      currentAdmin.permissions[module].push(action)
    }
    
    // 确保view权限始终存在
    if (currentAdmin.permissions[module].length > 0 && !currentAdmin.permissions[module].includes('view')) {
      console.log(`确保模块 ${module} 包含view权限`)
      currentAdmin.permissions[module].unshift('view')
    }
    
    console.log(`权限变更 ${module}.${action}:`, {
      module,
      action,
      newPermissions: currentAdmin.permissions[module],
      allPermissions: currentAdmin.permissions
    })
    
    this.setData({
      currentAdmin: currentAdmin
    })
  },

  // 检查权限是否被选中
  isPermissionSelected(module, action) {
    const currentAdmin = this.data.currentAdmin
    if (!currentAdmin) {
      console.log(`isPermissionSelected - currentAdmin不存在`)
      return false
    }
    
    const permissions = currentAdmin.permissions || {}
    const modulePermissions = permissions[module] || []
    
    // 确保modulePermissions是数组且包含action
    const isSelected = Array.isArray(modulePermissions) && modulePermissions.includes(action)
    
    // 添加调试日志
    console.log(`检查权限 ${module}.${action}:`, {
      module,
      action,
      currentAdmin: currentAdmin,
      permissions: permissions,
      modulePermissions: modulePermissions,
      isSelected: isSelected
    })
    
    return isSelected
  },

  // 简单的权限检查方法（用于WXML）
  checkPermission(module, action) {
    const currentAdmin = this.data.currentAdmin
    if (!currentAdmin || !currentAdmin.permissions) {
      return false
    }
    
    const modulePermissions = currentAdmin.permissions[module] || []
    return Array.isArray(modulePermissions) && modulePermissions.includes(action)
  },

  // 测试权限数据
  testPermissions() {
    console.log('=== 测试权限数据 ===')
    console.log('currentAdmin:', this.data.currentAdmin)
    console.log('permissions:', this.data.currentAdmin?.permissions)
    
    if (this.data.currentAdmin && this.data.currentAdmin.permissions) {
      this.data.permissionModules.forEach(module => {
        const modulePermissions = this.data.currentAdmin.permissions[module.key] || []
        console.log(`模块 ${module.key}:`, modulePermissions)
        
        this.data.permissionActions.forEach(action => {
          const isSelected = this.checkPermission(module.key, action.key)
          console.log(`  ${action.key}: ${isSelected}`)
        })
      })
      
      wx.showToast({
        title: '权限数据已输出到控制台',
        icon: 'none'
      })
    } else {
      wx.showToast({
        title: '权限数据不存在',
        icon: 'none'
      })
    }
  },

  // 保存管理员
  async onSave() {
    const admin = this.data.currentAdmin
    
    if (!admin.username.trim()) {
      wx.showToast({
        title: '请输入用户名',
        icon: 'none'
      })
      return
    }
    
    // 确保每个模块至少包含view权限
    if (admin.permissions) {
      this.data.permissionModules.forEach(module => {
        if (!admin.permissions[module.key] || admin.permissions[module.key].length === 0) {
          admin.permissions[module.key] = ['view'];
        } else if (!admin.permissions[module.key].includes('view')) {
          admin.permissions[module.key].unshift('view');
        }
      });
    }
    
    console.log('保存前的权限数据:', admin.permissions);
    
    if (!admin.nickname.trim()) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      })
      return
    }
    
    if (this.data.showAddModal) {
      if (!admin.password.trim()) {
        wx.showToast({
          title: '请输入密码',
          icon: 'none'
        })
        return
      }
      
      if (!admin.confirmPassword.trim()) {
        wx.showToast({
          title: '请输入确认密码',
          icon: 'none'
        })
        return
      }
      
      if (admin.password !== admin.confirmPassword) {
        wx.showToast({
          title: '两次输入的密码不一致',
          icon: 'none'
        })
        return
      }
    }
    
    try {
      let result
      const app = getApp()
      const globalData = app ? app.globalData : { token: '', baseUrl: '' }
      
      if (this.data.showAddModal) {
        // 创建管理员
        result = await new Promise((resolve, reject) => {
          wx.request({
            url: globalData.baseUrl + '/createAdmin',
            method: 'POST',
            data: admin,
            header: {
              'content-type': 'application/json',
              'Authorization': globalData.token ? 'Bearer ' + globalData.token : ''
            },
            success: (res) => {
              if (res.statusCode === 200) {
                resolve(res.data)
              } else {
                reject(res)
              }
            },
            fail: reject
          })
        })
      } else {
        // 更新管理员
        result = await new Promise((resolve, reject) => {
          wx.request({
            url: globalData.baseUrl + '/updateAdmin',
            method: 'POST',
            data: admin,
            header: {
              'content-type': 'application/json',
              'Authorization': globalData.token ? 'Bearer ' + globalData.token : ''
            },
            success: (res) => {
              if (res.statusCode === 200) {
                resolve(res.data)
              } else {
                reject(res)
              }
            },
            fail: reject
          })
        })
      }
      
      if (result.code === 1) {
        wx.showToast({
          title: this.data.showAddModal ? '创建成功' : '更新成功',
          icon: 'success'
        })
        this.closeModal()
        this.loadData()
      } else {
        wx.showToast({
          title: result.msg || '操作失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('保存管理员失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  },

  // 关闭模态框
  closeModal() {
    this.setData({
      showAddModal: false,
      showEditModal: false,
      currentAdmin: null,
      showPassword: false,
      showConfirmPassword: false,
      showEditPassword: false
    })
  },

  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return ''
    const date = new Date(timestamp * 1000)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
  },

  onPrevPage() {
    if (this.data.page > 1) {
      this.setData({
        page: this.data.page - 1
      })
      this.loadData()
    }
  },

  onNextPage() {
    if (this.data.page < this.data.totalPages) {
      this.setData({
        page: this.data.page + 1
      })
      this.loadData()
    }
  }
})
